package io.dcloud.uniplugin;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

public class VideoModule extends UniModule {
    String TAG = "VideoModule";
    public static int REQUEST_CODE = 1000;
    UniJSCallback uniCallback;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == REQUEST_CODE && data.hasExtra("videoPath")) {
                String videoPath = data.getStringExtra("videoPath");
                JSONObject res = new JSONObject();
                res.put("videoPath", videoPath);
                uniCallback.invoke(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @UniJSMethod(uiThread = true)
    public void watermark(JSONObject options, UniJSCallback jsCallback) {
        String path = options.getString("path").replace("file://", "");

//        'taskName':'莒南县创建国家卫生县城暗访',
//                'path': path,
//                'address': '济宁市·任城区·城投星城广场',
//                'longitude':'118.844991°E',
//                'latitude':'35.201878°N',
//                'date':'2023-10-19',
//                'time':'21:43',
//                'week':'星期四',
//                'altitude':'10米'

        String taskName = options.getString("taskName");
        String address = options.getString("address");
        float longitude = options.getFloat("longitude");
        float latitude = options.getFloat("latitude");
        String date = options.getString("date");
        String time = options.getString("time");
        String week = options.getString("week");
        //String altitude = options.getString("altitude");

        String fileDir = path;
        //compressedImage(fileDir);
        Log.e(TAG, "fileDir====--" + fileDir);
        Bitmap bitmap = BitmapFactory.decodeFile(fileDir);
        Integer height = bitmap.getHeight();
        Integer width = bitmap.getWidth();
        Bitmap result = Bitmap.createBitmap(width, height, bitmap.getConfig());

        float textSize1 = 80;//字体大小1 40
        float textSize2 = 200;//字体大小2 100
        float alpha = 1;//透明度

        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(3);
        paint.setAlpha((int) (255 * alpha));
        paint.setAntiAlias(true);
        paint.setUnderlineText(false);

        //海拔
        paint.setTextSize(textSize1);
        //canvas.drawText(String.format("海拔：%s",altitude), 50, height - 50, paint);
        //经纬度
        String mark1 = "°N";
        String mark2 = "°E";
        if (latitude < 0) {
            mark1 = "°S";
        }
        if (longitude < 0) {
            mark2 = "°W";
        }
        canvas.drawText(String.format("经纬度：%f%s,%f%s", Math.abs(latitude), mark1, Math.abs(longitude), mark2), 50, height - 200, paint);
        //地址
        canvas.drawText(address, 50, height - 300, paint);
        //时间
        paint.setTextSize(textSize2);
        canvas.drawText(time, 50, height - 400, paint);
        //分割线
        Paint paintLine = new Paint();
        paintLine.setColor(Color.rgb(255, 194, 51)); // 设置线条颜色
        paintLine.setStrokeWidth(20); // 设置线条宽度
        paintLine.setAntiAlias(true);
        canvas.drawLine(590, height - 560, 590, height - 390, paintLine); //画线

        //日期
        paint.setTextSize(textSize1);
        canvas.drawText(date, 650, height - 400, paint);
        //星期
        canvas.drawText(week, 650, height - 500, paint);
        //任务名称
        canvas.drawText(taskName, 50, height - 600, paint);

        //保存
        String thumbUrl = saveBitmapAsPng(result, path);
        JSONObject res = new JSONObject();
        res.put("thumbUrl", thumbUrl);
        jsCallback.invoke(res);
    }
    /**
     * 压缩
     *
     * @param fileDir
     */
    public void compressedImage(String fileDir) {
        try {
            Bitmap originalImage = BitmapFactory.decodeFile(fileDir);
            // 设置目标宽度和高度（根据需要调整）
            int targetWidth = 1920; // 目标宽度
            int targetHeight = 2560; // 目标高度
            int sWidth = originalImage.getWidth();
            int sHeight = originalImage.getHeight();
            if (sWidth > sHeight) {
                targetWidth = 2560;
                targetHeight = 1920;
            }
            // 计算压缩比例
            float scaleFactor = Math.min(((float) targetWidth) / sWidth, ((float) targetHeight) / sHeight);

            // 创建新的bitmap对象并将其作为输入参数传递到createScaledBitmap()函数中
            Bitmap compressedImage = Bitmap.createScaledBitmap(originalImage, (int) (scaleFactor * originalImage.getWidth()), (int) (scaleFactor * originalImage.getHeight()), true);

            // 保存压缩后的图片至指定路径
            compressedImage.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(fileDir));

            // 最后记得释放内存
            originalImage.recycle();
            compressedImage.recycle();
        } catch (FileNotFoundException e) {

        }
    }

    public String saveBitmapAsPng(Bitmap bmp, String path) {
        try {
            File f = new File(path);
            FileOutputStream out = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return path;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

//    @UniJSMethod(uiThread = true)
//    public void getVideoThumb(JSONObject options, UniJSCallback jsCallback) {
//        String path = options.getString("path").replace("file://","");
//        String packageName = options.getString("packageName");
//        Log.e(TAG, "path====--"+path);
//        Reference<MediaMetadataRetriever> retriever = new WeakReference<>(new MediaMetadataRetriever());
//        retriever.get().setDataSource(path);
//        String duration = retriever.get().extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
//        Bitmap bitmap = retriever.get().getFrameAtTime(Integer.parseInt(duration) * 1000, MediaMetadataRetriever.OPTION_CLOSEST);
//        String thumbUrl = saveBitmapAsPng(bitmap,packageName);
//        JSONObject res = new JSONObject();
//        res.put("thumbUrl", thumbUrl);
//        jsCallback.invoke(res);
//    }

//    public String saveBitmapAsPng(Bitmap bmp,String packageName) {
//        try {
//            String fileDir = getSdPath() + "/Android/data/"+packageName+"/Thumb/";
//            File dir = new File(fileDir);
//            if(!dir.exists()){
//                dir.mkdirs();
//            }
//            String fileName = System.currentTimeMillis() + ".png";
//            String path = fileDir + fileName;
//            File f = new File(path);
//            FileOutputStream out = new FileOutputStream(f);
//            bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
//            out.flush();
//            out.close();
//            return path;
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    /**
     * 获取SD path
     *
     * @return
     */
    public String getSdPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
            return sdDir.toString();
        }
        return null;
    }


    @UniJSMethod(uiThread = true)
    public void gotoVideoPage(UniJSCallback jsCallback) {
        uniCallback = jsCallback;
//        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//        //设置视频录制的最长时间
//        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 15);
//        //设置视频录制的画质
//        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//        ((Activity)mUniSDKInstance.getContext()).startActivityForResult(intent, VIDEO_WITH_CAMERA);


//        Log.e("VideoModule", "原生页面返回----");
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = new Intent(mUniSDKInstance.getContext(), VideoActivity.class);
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }
}
